package queue.model;

import distributions.ExponentialStream;
import java.io.IOException;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mostafa
 */
public class SystemRunner implements Observer {

    private static final int MAX_NUM_ENTRIES = 20;

    private MachineCenter m1;
    private InspectionStation m2;
    private ExponentialStream exponentialDis;

    public SystemRunner() {
        m1 = new MachineCenter("Machining Center", this);
        m2 = new InspectionStation("Inspection Station", this);
        exponentialDis = new ExponentialStream(1);
    }

    public static void main(String[] args) throws InterruptedException {
        SystemRunner system = new SystemRunner();
        system.run();
    }

    public void update(Observable machine, Object arg) {
        Item item = (Item) arg;

        if (machine.equals(m1))
            m2.scheduleArrival(item);
        else if (machine.equals(m2)) {
            if (item.isGood()) {
                // TODO exit the system
                System.out.println("Good item " + item + " exiting");
                item.setDepartureDate(new Date());
            } else {
                System.out.println("Bad item " + item + " rescheduling");
                m1.scheduleArrival(item);
            }
        }
    }

    public void run() {
        long acc = new Date().getTime();
        for (int i = 0; i < MAX_NUM_ENTRIES; i++) {
            try {
                acc += (long) (InspectionStation.TIME_TRANSLATION_CONST * exponentialDis.getNumber());
            } catch (IOException ex) {
                Logger.getLogger(SystemRunner.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ArithmeticException ex) {
                Logger.getLogger(SystemRunner.class.getName()).log(Level.SEVERE, null, ex);
            }
            m1.scheduleArrival(new Item(i+1, new Date(acc)));
        }
    }
}
